#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include "golfdds.h"
#include "ring_queue.h"
#include "golfdds_shm.h"
#include <pthread.h>

#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <sys/select.h>
PUBSUBINFO *g_pubsubinfo = NULL;

void savepubsub(PUBSUBINFO *info)
{
    PUBSUBINFO *tmpinfo = g_pubsubinfo;
    while (tmpinfo != NULL)
    {
        if (0 == strcmp(tmpinfo->pubinfo.topicname, info->subinfo.topicname) &&
            tmpinfo->type == info->type)
        {
            // printf("has exist publisher's info,just return!\n");
            return;
        }
        tmpinfo = tmpinfo->next;
    }
    printf("will really save pubsub's info to memory!\n");
    printf("type:%d,node:%s\ntopic:%s\nshmpath:%s\n", info->type, info->pubinfo.nodename, info->pubinfo.topicname, info->pubinfo.shmpath);
    PUBSUBINFO *tmpnew = (PUBSUBINFO *)calloc(1, sizeof(PUBSUBINFO));
    *tmpnew = *info;
    tmpnew->next = g_pubsubinfo;
    g_pubsubinfo = tmpnew;
}
PUBSUBINFO *searchpubsub(PUBSUBTYPE type, const char *topicname)
{
    PUBSUBINFO *tmpinfo = g_pubsubinfo;
    while (tmpinfo != NULL)
    {
        if (0 == strcmp(tmpinfo->pubinfo.topicname, topicname) && tmpinfo->type == type)
        {
            // printf("got publisher info of:%s,willreturn !\n", info->subinfo.topicname);
            return tmpinfo;
        }
        tmpinfo = tmpinfo->next;
    }
    printf("fail to find pubsubtype:%d, of topic:%s\n", type, topicname);
    return NULL;
}
int main(int argc, const char *argv[])
{
    // 简单的udp服务器，订阅者和发布者都可以发布信息过来
    // 发布者发布信息过来存着，订阅者得到主题信息
    // 1、建立套接字，使用IPV4网络地址，UDP协议
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1)
    {
        perror("create_broadcastrecvsock-socket fail");
        return 0;
    }

    // 2、设置端口复用（推荐）
    int optval = 1; // 这里设置为端口复用，所以随便写一个值
    int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
    if (ret == -1)
    {
        perror("create_broadcastrecvsock-setsockopt fail");
        close(sockfd);
        return 0;
    }

    // 3、绑定自己的IP地址和端口号（可以省略）
    socklen_t addr_len = sizeof(struct sockaddr);
    struct sockaddr_in recv_addr;
    bzero(&recv_addr, sizeof(recv_addr));
    recv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    recv_addr.sin_family = AF_INET;   // 指定协议为IPV4地址协议
    recv_addr.sin_port = htons(9527); // 端口号

    ret = bind(sockfd, (struct sockaddr *)&recv_addr, addr_len);
    if (ret == -1)
    {
        perror("create_broadcastrecvsock-bind fail");
        close(sockfd);
        return 0;
    }

    fd_set rfds;
    struct timeval tv;
    int retval;
    while (1)
    {
        FD_ZERO(&rfds);

        FD_SET(sockfd, &rfds);

        tv.tv_sec = 1;
        tv.tv_usec = 0;

        retval = select(sockfd + 1, &rfds, NULL, NULL, &tv);
        if (retval == -1)
        {
            perror("select");
        }
        else if (retval)
        {
            char buffer[1024];
            struct sockaddr_in cliaddr;
            socklen_t addrlen = sizeof(cliaddr);

            if (FD_ISSET(sockfd, &rfds))
            {
                ssize_t len = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&cliaddr, &addrlen);
                if (len > 0)
                {
                    PUBSUBINFO *info = (PUBSUBINFO *)buffer;
                    savepubsub(info);
                    if (info->type == PUBLISHER)
                    { // recv publisher info,save to memory
                      // printf("recv publisher info,will save publisher's info!\n");

                        PUBSUBINFO *subinfo = searchpubsub(SUBSCRIBER, info->pubinfo.topicname);
                        if (subinfo != NULL)
                        {
                            // printf("has find publisher's info,will send to subscriber's node,port:%d!\n", info->nodeport);
                            udpsend(subinfo, sizeof(PUBSUBINFO), "127.0.0.1", info->nodeport);
                        }
                    }
                    else if (info->type == SUBSCRIBER)
                    { // recv subscriber request info, search publisher info in memory and send publisher info to subscriber
                        // printf("recv subscriber info,will search publisher of topic:%s in memory!\n", info->subinfo.topicname);

                        PUBSUBINFO *pubinfo = searchpubsub(PUBLISHER, info->subinfo.topicname);
                        if (pubinfo != NULL)
                        {
                            // printf("has find publisher's info,will send to subscriber's node,port:%d!\n", info->nodeport);
                            udpsend(pubinfo, sizeof(PUBSUBINFO), "127.0.0.1", info->nodeport);
                        }
                    }
                }
                /* SUBSCRIBERINFO* psubinfo=(SUBSCRIBERINFO*)buffer;

                    if(0!=strcmp(psubinfo->nodename,inst->nodename)){
                        struct timeval tv;
                        gettimeofday(&tv,NULL);
                        double now=(double)tv.tv_sec+(double)tv.tv_usec/1000000.0;
                        printf("%f,recv subscribe info:%s,%s,%d\n",now,psubinfo->nodename,psubinfo->topicname,psubinfo->subscriberport);
                        //这里收到订阅者的信息，核对后如果publisher提供了该主题名称，则发送该主题相关信息如：路径，shmid,消息大小，消息队列长度

                        GOLFDDS_PUBLISHER_INSTANCE* tmppub=inst->publisher;
                        while(tmppub!=NULL){
                        if(0==strcmp(tmppub->topicname,psubinfo->topicname)){
                            PUBLISHERINFO pubinfo;
                            strcpy(pubinfo.nodename,inst->nodename);
                            strcpy(pubinfo.topicname,tmppub->topicname);
                            strcpy(pubinfo.shmpath,tmppub->shmpath);
                            pubinfo.shmid=tmppub->shmid;
                            pubinfo.msgsize=tmppub->msgsize;
                            pubinfo.queuelen=tmppub->queuelen;

                                    // 4、发送数据
                            struct sockaddr_in recv_addr = {0};

                            // 注意输入广播地址，格式为*.*.*.255
                            recv_addr.sin_family = AF_INET;                       // 指定用IPV4地址
                            recv_addr.sin_port = htons(psubinfo->subscriberport);                     // 接收者的端口号
                            recv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 接收者的IP地址

                            if(tmppub->subscribernum==0)tmppub->subscribernum=1;
                            {
                            socklen_t addr_len = sizeof(struct sockaddr);
                            // 发送数据，注意要填写接收者的地址
                            int ret = sendto(inst->sockfd, &pubinfo, sizeof(PUBLISHERINFO), 0,
                                        (struct sockaddr *)&recv_addr, addr_len);
                            if (ret > 0)
                            {
                            // printf("attach_subscriber-success: send %d bytes,%d\n", ret,sub->sockfd);
                            }
                            }
                        }
                        tmppub=tmppub->next;
                        }
                    }*/
            }
        }
        else
        {
            // printf("Timeout,%d\n", retval);
        }
    }

    return 0;
}